package com.bml.architect.rocketmq.producer;


import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

import java.util.function.Function;

/**
 * 利用了扩展的extRocketMQTemplate来监听事务
 * 在spring boot的rocketmq中，一个监听器只能监听一个RocketMqTempate的事务，如果有两种业务的事务
 * 就可以扩展一个RocketMqTempate 来使用
 */
@RocketMQTransactionListener(rocketMQTemplateBeanName = "extRocketMQTemplate")
public class TransactionExtMsg implements RocketMQLocalTransactionListener {
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        Function<String, Integer> function = Integer::valueOf;
        int i = function.apply(arg.toString());
        if (i < 2) {
            return RocketMQLocalTransactionState.ROLLBACK;
        } else if (i > 5) {
            return RocketMQLocalTransactionState.COMMIT;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        System.out.println("事务检查成功");
        return RocketMQLocalTransactionState.COMMIT;
    }
}
